package com.np.moneylover;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.np.dao.JSONParser;
import com.np.dao.KeHoachData;
import com.np.dao.KeHoachDataListener;
import com.np.dao.LoaiGiaoDichData;
import com.np.dao.LoaiGiaoDichDataListener;
import com.np.dao.SoThuChiData;
import com.np.dto.KeHoach;
import com.np.dto.LoaiGiaoDich;
import com.np.moneylover.DangKy.Taikhoa_action;

import Util.Constants;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;

public class Thu extends Activity implements OnClickListener,
		KeHoachDataListener, LoaiGiaoDichDataListener {
	EditText txtkhoanthu = null;
	EditText txtsotien = null;
	EditText txtghichu = null;
	EditText txtngaythu = null;
	Spinner spkehoach = null;
	Spinner sptheloai = null;
	Button btnthemluu = null;
	Button btnluu = null;
	
	public String mess;
	private List<KeHoach> lstkehoach;
	public KeHoach dataLMClick;
	private List<LoaiGiaoDich> lstlgiaodich;
	private LoaiGiaoDich datalgdClick;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.thu);
		txtkhoanthu = (EditText) findViewById(R.id.txtkhoanthu);
		txtsotien = (EditText) findViewById(R.id.txtsotien);
		txtngaythu = (EditText) findViewById(R.id.dtpngaythu);
		txtghichu = (EditText) findViewById(R.id.txtghichu);
		spkehoach = (Spinner) findViewById(R.id.spkehoach);
		sptheloai = (Spinner) findViewById(R.id.sptheloai);
		btnthemluu = (Button) findViewById(R.id.btnluuthem);
		btnluu = (Button) findViewById(R.id.btnluu);
		btnthemluu.setOnClickListener(this);
		btnluu.setOnClickListener(this);
		txtngaythu.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				// Launching All products Activity
				showDatePickerDialog();
			}
		});
		Loadreference();

	}

	private void Loadreference() {
		// TODO Auto-generated method stub
		// 1. the loai thu
		LoadLoaiThu();

		// lấy ngày hiện tại của hệ thống
		cal = Calendar.getInstance();
		SimpleDateFormat dft = null;
		// Định dạng ngày / tháng /năm
		dft = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
		String strDate = dft.format(cal.getTime());
		// hiển thị lên giao diện
		txtngaythu.setText(strDate);

		dateFinish = cal.getTime();

		// 2. load ke hoach
		Loadkehoach();

	}

	private void LoadLoaiThu() {
		// TODO Auto-generated method stub
		String url = "http://10.0.2.2:8080/connect_android/getloaigiaodich.php?magd='1'";
		LoaiGiaoDichData task = new LoaiGiaoDichData(this);
		task.execute(url);
	}

	private void Loadkehoach() {
		// TODO Auto-generated method stub
		// ProgressDialog.show(this, "", "Kiểm tra đăng nhập ...");
		// chay localhost thi la 10.0.2.2

		String url = "http://10.0.2.2:8080/connect_android/getkehoach.php";
		KeHoachData task = new KeHoachData(this);
		task.execute(url);

	}

	Calendar cal;
	Date dateFinish;
	public String url1;

	public void showDatePickerDialog() {
		OnDateSetListener callback = new OnDateSetListener() {

			@Override
			public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
				// TODO Auto-generated method stub
				txtngaythu.setText((arg3) + "/" + (arg2 + 1) + "/" + arg1);
				// Lưu vết lại biến ngày hoàn thành
				cal.set(arg1, arg2, arg3);
				dateFinish = cal.getTime();
			}
		};
		// các lệnh dưới này xử lý ngày giờ trong DatePickerDialog
		// sẽ giống với trên TextView khi mở nó lên

		String s = txtngaythu.getText() + "";
		String strArrtmp[] = s.split("/");
		int ngay = Integer.parseInt(strArrtmp[0]);
		int thang = Integer.parseInt(strArrtmp[1]) - 1;
		int nam = Integer.parseInt(strArrtmp[2]);
		DatePickerDialog pic = new DatePickerDialog(Thu.this, callback, nam,
				thang, ngay);
		pic.setTitle("Chọn ngày hoàn thành");
		pic.show();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int id = v.getId();
		switch (id) {
		case R.id.btnluuthem:
			// insert du lieu quay ve man hinh giao dich

			if (invalid().equals("")) {
				url1 = "http://10.0.2.2:8080/connect_android/thuchi_them.php";
				Thu_action task = new Thu_action();
				task.execute(url1);
				if(mess.equals("1")){
				   Intent I= new Intent(this,GiaoDich.class);
				   startActivity(I);
						   
				}
				else
				{
					AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this);                      
				    dlgAlert.setMessage("Thêm khoản thu không thành công");
				    dlgAlert.setTitle("Thông báo");              
				    dlgAlert.setPositiveButton("OK", null);
				    dlgAlert.setCancelable(false);
				    dlgAlert.create().show();
					
				}
			}
			else
			{
				AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this);                      
			    dlgAlert.setMessage(invalid());
			    dlgAlert.setTitle("Thông báo");              
			    dlgAlert.setPositiveButton("OK", null);
			    dlgAlert.setCancelable(false);
			    dlgAlert.create().show();
			}

			break;
		case R.id.btnluu:
			// insert xong quay ve man hinh so chi tieu

			if (invalid().equals("")) {
				url1 = "http://10.0.2.2:8080/connect_android/thuchi_them.php";
				Thu_action task2 = new Thu_action();
				task2.execute(url1);
				if(mess.equals("1")){
					   Intent I= new Intent(this,SoChiTieu.class);
					   startActivity(I);
							   
					}
				else
				{
					AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this);                      
				    dlgAlert.setMessage("Thêm khoản thu không thành công");
				    dlgAlert.setTitle("Thông báo");              
				    dlgAlert.setPositiveButton("OK", null);
				    dlgAlert.setCancelable(false);
				    dlgAlert.create().show();
				}
			}
			else
			{
				AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this);                      
			    dlgAlert.setMessage(invalid());
			    dlgAlert.setTitle("Thông báo");              
			    dlgAlert.setPositiveButton("OK", null);
			    dlgAlert.setCancelable(false);
			    dlgAlert.create().show();
			}
			break;

		default:
			break;
		}
	}

	public String invalid() {
		String errors = "";
		if (txtkhoanthu.getText().toString().trim().equals("")) {
			errors += "\nKhoản thu chưa nhập";
		}
		if (txtsotien.getText().toString().trim().equals("")) {
			errors += "\nSố tiền chưa nhập";
		} else {
			try {
				Float.parseFloat(txtsotien.getText().toString());

			} catch (Exception e) {
				// TODO: handle exception
				errors += "\nSố tiền không hợp lệ";

			}
		}
		return errors;

	}

	@Override
	public void onGetListKeHoachComplete(List<KeHoach> data) {
		// TODO Auto-generated method stub
		lstkehoach = data;

		List<String> list = new ArrayList<String>();
		for (int i = 0; i < lstkehoach.size(); i++) {
			String temp = lstkehoach.get(i).getTenKH().toString();
			list.add(temp);

		}

		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, list);
		dataAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spkehoach.setAdapter(dataAdapter);
		spkehoach.setOnItemSelectedListener(new KeHoachSelected());

	}

	class KeHoachSelected implements OnItemSelectedListener {

		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {
			dataLMClick = lstkehoach.get(pos);

		}

		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
		}
	}

	@Override
	public void onGetListKeHoachFailure(String msg) {
		// TODO Auto-generated method stub

	}

	class LoaGiaoDichSelected implements OnItemSelectedListener {

		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {
			datalgdClick = lstlgiaodich.get(pos);

		}

		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
		}
	}

	// Tao mot class lo viec ThemXoaSua Taikhoan
	class Thu_action extends AsyncTask<String, String, String> {
		ProgressDialog Pdialog = null;
		int success = 0;
		String msg = "";
		String test = "";

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			Pdialog = new ProgressDialog(Thu.this);
			Pdialog.setMessage("Đang thực hiện giao dịch..");
			Pdialog.setIndeterminate(false);
			Pdialog.setCancelable(true);
			Pdialog.show();
		}

		protected String doInBackground(String... params) {
			if (params == null)
				return null;
			JSONParser jsonParser = new JSONParser();
			// get url from params
			List<NameValuePair> arrays = new ArrayList<NameValuePair>();

			arrays.add(new BasicNameValuePair("tengd", txtkhoanthu.getText()
					.toString().trim()));
			arrays.add(new BasicNameValuePair("sotien", txtsotien.getText()
					.toString().trim()));
			arrays.add(new BasicNameValuePair("laplai", "0"));
			arrays.add(new BasicNameValuePair("ngaygd", "2013-8-9"));
			arrays.add(new BasicNameValuePair("ghichu", txtghichu.getText()
					.toString().trim()));
			arrays.add(new BasicNameValuePair("maloaigd", Integer
					.toString(datalgdClick.ID)));
			arrays.add(new BasicNameValuePair("magd", "1"));
			arrays.add(new BasicNameValuePair("username", Constants._login
					.getUser().toString()));
			arrays.add(new BasicNameValuePair("makh", Integer
					.toString(dataLMClick.ID)));

			JSONObject json = jsonParser.makeHttpRequest(url1, "POST", arrays);
			try {
				success = json.getInt("success");
				test = json.getString("message");

				/*if (success == 1) {
					// successfully created product

					msg = "thanhcong";
					return null;

				} else {
					// failed to create product
					msg = "That bai";
					return null;
				}*/
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;
		}

		protected void onPostExecute(String file_url) {
			// dismiss the dialog once done
			Pdialog.dismiss();

			if (success == 1) {
				
                mess="1";
			}
			else
			{
				mess="2";
			}

		}
	}

	@Override
	public void onLoaiLoaiGiaoDichComplete(List<LoaiGiaoDich> data) {
		// TODO Auto-generated method stub
		lstlgiaodich = data;

		List<String> list = new ArrayList<String>();
		for (int i = 0; i < lstlgiaodich.size(); i++) {
			String temp = lstlgiaodich.get(i).getTenLoaiGD().toString();
			list.add(temp);

		}

		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, list);
		dataAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sptheloai.setAdapter(dataAdapter);
		sptheloai.setOnItemSelectedListener(new LoaGiaoDichSelected());

	}

	@Override
	public void onLoaiGiaoDichFailure(String msg) {
		// TODO Auto-generated method stub

	}
}
